<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增产品' : '编辑商品'" width="900px">
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="80px">
      <el-alert
        title="产品信息"
        type="success"
        :closable="false" style="margin-bottom:15px;">
      </el-alert>
      <el-form-item label="产品名称" required prop="productName">
        <el-input v-model="form.productName" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="商品分类" required prop="classify3"> 
        <el-cascader v-model="form.classify3" :options="cates" :props="{value:'id',label:'categoryName'}" @change="cateChange()" style="width: 500px;" placeholder="选择商品分类"/>
      </el-form-item>
      <el-form-item label="品牌" required prop="brand">
        <template>
          <el-select v-model="form.brand" placeholder="请选择" style="width: 500px;">
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.brandName"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="副标题" required prop="subtitle">
        <el-input v-model="form.subtitle" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="包装列表" required  prop="packlist">
        <el-input v-model="form.packlist" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="售后服务" required  prop="afterservice">
        <el-input v-model="form.afterservice" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="产品状态" required >
        <el-radio v-model="form.status" :label="0">未申请</el-radio>
        <el-radio v-model="form.status" :label="1">申请中</el-radio>
        <el-radio v-model="form.status" :label="2">审核通过</el-radio>
        <el-radio v-model="form.status" :label="3">已驳回</el-radio>
      </el-form-item>
      <el-form-item label="产品介绍">
        <editor v-model="introduce" />
      </el-form-item>
      <el-alert
        title="属性信息"
        type="success"
         :closable="false" style="margin-bottom:15px;">
      </el-alert>
        <div v-for="attr in attributes" :key="attr.index">
          <el-tag style="width:850px;margin-bottom:15px;">{{attr.group}}</el-tag>
            <el-form-item :label="item.name" v-for="item in attr.item" :key="item.index" style="width:300px;"  >
              <el-input type="text" v-model="item.value" ></el-input>
            </el-form-item>
        </div>
        <el-alert
          title="商品信息"
          type="success"
           :closable="false" style="margin-bottom:15px;">
        </el-alert>
      <div class="filter-container">
     <!-- <el-button type="primary" @click="init()" icon="el-icon-circle-plus">add</el-button> -->
   </div> 
    <el-form-item label="商品规格：" >
      <el-button  @click="addNature"  type="success">增加属性</el-button>
      <el-button @click="addSku" type="success">增加商品</el-button>
     </el-form-item>
   <el-table :data="goodsList" border>
            <el-table-column prop="goodsName" label="商品名称">
                <template slot-scope="scope">
                    <el-input size="mini"  v-model="scope.row['goodsName']" placeholder="请输入内容" :disabled="scope.row['editable']" required></el-input>
                    <!-- <span v-show="!scope.row.show">{{scope.row.goodsName}}</span> -->
                </template>
            </el-table-column>
            <el-table-column prop="costPrice" label="供价">
                <template slot-scope="scope">
                    <el-input size="mini"  v-model="scope.row['costPrice']" placeholder="请输入内容" :disabled="scope.row['editable']" required></el-input>
                    <!-- <span v-show="!scope.row.show">{{scope.row.costPrice}}</span> -->
                </template>
            </el-table-column>
            <el-table-column prop="sellPrice" label="售价">
                <template slot-scope="scope">
                    <el-input size="mini"  v-model="scope.row['sellPrice']" placeholder="请输入内容" :disabled="scope.row['editable']"></el-input>
                    <!-- <span v-show="!scope.row.show">{{scope.row.sellPrice}}</span> -->
                </template>
            </el-table-column>
            <el-table-column prop="inventory" label="库存">
                <template slot-scope="scope">
                    <el-input size="mini"  v-model="scope.row['inventory']"  placeholder="请输入内容" :disabled="scope.row['editable']"></el-input>
                    <!-- <span v-show="!scope.row.show">{{scope.row.inventory}}</span> -->
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center"> 
                <el-tag  type="success">上架</el-tag>
          </el-table-column>
            <!-- 自定义部分 -->
                <el-table-column v-for="(col,i ) in attr_names" :prop="col.prop" :key="i">
                  <template slot="header" slot-scope="scope">
                    <span class="del" v-on:click="delColumn(scope.$index)" v-if="editType">X</span>
                    <el-input v-model="col.label" size="mini" class="f-cent" :disabled="!editType"/>
                  </template>
                  <template slot-scope="scope">
                    <el-input size="mini" v-model="scope.row[col.prop]" :disabled="scope.row['editable']"> </el-input>
                  </template>
                </el-table-column>
            <el-table-column fixed="right" label="操作" width="50">
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="deleteRow(scope.$index, goodsList)"
                      type="text"
                      size="small" v-if="!scope.row['editable']">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
        </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCates } from '@/api/StoreCategory'
import {getBrandsAndAttr} from '@/api/storeTemplate'
import { add, edit } from '@/api/StoreProduct'
import editor from '../../components/Editor'
import picUpload from '@/components/pic-upload'
import mulpicUpload from '@/components/mul-pic-upload'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MaterialList from '@/components/material'
import Cookies from 'js-cookie'
export default {
  components: { editor, picUpload, mulpicUpload, Treeselect, MaterialList },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false, dialog: false, cates: [],brands:[],attributes:[],
      dialogFormVisible:false,
      editType:true, //判定商品属性标签是否可编辑
      attr_names: [ 
                  // 为了方便理解用 保留
                  // {label: '成本', prop: 'cost_price'},
                  // {label: '售价', prop: 'price'},
                  // {label: '库存', prop: 'quantity'}, 
                  // {label: '货号', prop: 'no'},
              ],
      form: {
        id: '',
        productName:'',
        status:2,
        shopId:0,
        classify3:'',
        brand:'',
        subtitle: '',
        packlist:'',
        afterservice:'',
        goodsList:[],
        bak1:'',
        bak2:''
        
      },
      introduce:'',
      goodsList:[{ goodsName: '', costPrice:'',sellPrice: '',inventory:'',status:1,specInfo:''}],
      rules: {
         productName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        classify3: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        brand: [
          { required: true, message: '请选择品牌', trigger: 'blur' }
        ],
        subtitle: [
          { required: true, message: '请输入副标题', trigger: 'blur' }
        ],
        packlist: [
          { required: true, message: '请输入包装列表', trigger: 'blur' }
        ],
        afterservice: [
          { required: true, message: '请选择品牌输入售后服务', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    value: function(val) {
      this.editor.txt.html(val)
      // this.editor.txt.html(val)
    }
  },
  // mounted: {
  //   initDomains()
  // },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      // this.loading = true
        this.doAdd()
      
    },
    doAdd() {
      this.$refs['form'].validate((valid) => {
      if (valid) {
      this.form.shopId=Cookies.get('shopId');
      const attrArr=this.attributes;
      
      const specName=this.attr_names;
      const goodList=this.goodsList;
       //组装attribute为json格式
       const attributeArr=this.attributes;
      const attrJson=[];
      for(let i=0;i<attributeArr.length;i++){
        const names=attributeArr[i].item;
        const nameArr=[];
        for(let j=0;j<names.length;j++){
          const name='"name":"'+names[j].name+'"';
          nameArr.push("{"+name+"}")
        }
        const json='"group":"'+attributeArr[i].group+'","item":['+nameArr.join(",")+']';
        attrJson.push("{"+json+"}")
      }
      //console.log(attrJson.join(","),"attrJson")

       //组装规格specInfo为json格式
      for(let j=0;j<this.goodsList.length;j++){
        const spec=[];
            for(let i=0;i<specName.length;i++){
              if(i==0){
                const specStr='"'+specName[i].label+'":"'+goodList[j].attr_0+'"'
                spec.push('{'+specStr+'}')
              }else if(i==1){
                const specStr='"'+specName[i].label+'":"'+goodList[j].attr_1+'"'
                spec.push('{'+specStr+'}')
              }
              
            }
            goodList[j].specInfo="["+spec.join(",")+"]";
            //console.log(goodList[j].specInfo,"goodlist1Spec")     
      }
      this.form.classify3=this.form.classify3.pop()
     // 组装map
     this.form.goodsList=this.goodsList;
     this.form.bak1=attrJson.join(",")
     this.form.bak2=this.introduce
     //console.log(this.form,"=====================form")
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.queryList()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    } else {
          return false
        }
    })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.queryList()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
         id: '',
        productName:'',
        status:2,
        shopId:0,
        classify3:'',
        brand:'',
        subtitle: '',
        packlist:'',
        afterservice:'',
        bak1:'',
        bak2:''
      }
      this.introduce=''
      this.goodsList=[{ goodsName: '', costPrice:'',sellPrice: '',inventory:'',status:1,specInfo:''}]
      this.attributes=[]
    },
    getCates() {
      getCates({ enabled: true }).then(res => {
        this.cates = res.data.list
      })
    },
    cateChange(){ 
      if(this.form.classify3==null){
        return false;
      }
      const classify3=this.form.classify3
      getBrandsAndAttr(classify3[2]).then(res=>{
        this.brands=JSON.parse(res.data.brands);
        this.attributes=JSON.parse(res.data.attribute);
      })
    },
    // 增加商品属性
                addNature(){
                  let len=this.attr_names.length;
                  //新增以 attr_ 开关，也可以自行定义
                  this.attr_names.push({label: '商品规格', prop: `attr_${len}`})
                },
                // 增加商品SKU
                addSku(){
                  let data=this.goodsList[0]
                  let keys=[]
                  for (var key in data){
                      keys.push(key);
                  }
                  let obj={}
                  for(let i=0; i<keys.length; i++){
                    if(keys[i]==='editable'){
                      obj[keys[i]]=true
                    }else{
                      obj[keys[i]]=''
                    }
                  }
                  this.goodsList.push(obj);
                },
                //删除一排   tableData ARR
                deleteRow(index, rows) {
                  rows.splice(index, 1);
                },
                //删除SKU列 每次删除最后一列数据
                delColumn(index){
                  let len=this.attr_names.length - 1 ;
                  let str=this.attr_names[len].prop;
                  this.tableData.map((item)=>{
                    delete item[str];
                  })
                  this.attr_names.pop()
                }
  }
}
</script>

<style scoped>
 .del{
        cursor: pointer;
        display: none;
        background: red;
        color: #fff;
        font-size: 10px;
        padding: 2px 5px;
        position: absolute;
        top: 7px;
        right: 0px;
        z-index: 9;
        border-radius: 3px;
      }
      .cell:hover .del{
        display: inline;
      }

    .el-form--inline .el-form-item {
    margin-right: 15px;
    margin-left: 20px;
}
  .el-form-item__label{
    width: 120px;
    margin-left: -25px;
  }
</style>
